package com.shass.mybatis.aop;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class LogAop {
	
	private static final Logger logger = LoggerFactory.getLogger(LogAop.class);

	@Pointcut("execution (public * com.shass.mybatis.controller.*.*(..))")
	public void sysLog(){} 
	
	@Around("sysLog()")
	public Object arroud(ProceedingJoinPoint pjp){
//		MethodSignature methodSignature = (MethodSignature)pjp.getSignature();
//		Method targetMethod = methodSignature.getMethod();
//		
//		String className = methodSignature.getDeclaringTypeName()+"."+targetMethod.getName()+"()" ;
		
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = (HttpServletRequest) sra.getRequest();
		
		String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
		
		try {
			queryString = (queryString==null?"":URLDecoder.decode(queryString,"UTF-8"));
			logger.info("请求开始, 各个参数, url: {}, method: {}, uri: {}, params: {}", url, method, uri,queryString );
		} catch (UnsupportedEncodingException e1) {
		}
		
		Object obj = null ;
		try {
			obj = pjp.proceed();
		} catch (Throwable e) {
			e.printStackTrace();
		}  
		
		logger.info("请求结束，controller的返回值是: " + obj);
		
		return obj ;
	}
}
